package p03_bean生命周期;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 这是一个自定义的bean后处理器，被放入容器，该bean后处理器就会被运行
 * InstantiationAwareBeanPostProcessor接口表示初始化后处理器接口
 * DestructionAwareBeanPostProcessor表示销毁后处理器接口
 * bean生命周期的各个阶段，都会从容器中得到对应的所有bean后处理器类型的bean，然后依次回调某些对应的方法，典型的模板方法模式
 */
@Slf4j
@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {
    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        if (beanName.equals("bean")) {
            log.warn("<<<<<<<<<<销毁之前执行");
        }
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanName.equals("bean")) {
            log.warn("<<<<<<<<<<实例化之前执行,这里返回的对象会替换掉原本的bean");
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (beanName.equals("bean")) {
            log.warn("<<<<<<<<<<实例化之后执行,这里返回的false会跳过依赖注入阶段");
        }
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if (beanName.equals("bean")) {
            log.warn("<<<<<<<<<<依赖注入阶段执行,这里返回的值会替换原本的值,@Autowired,@Value,@Resource");
        }
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("bean")) {
            log.warn("<<<<<<<<<<初始化之前执行,这里返回的bean会替换原本的bean");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("bean")) {
            log.warn("<<<<<<<<<<初始化之后执行,这里返回的bean会替换原本的bean");
        }
        return bean;
    }
}
